<!--待审核付款申请编辑页（各级审批人在该页面审批）-->
<template>
  <div v-loading="loading">
    <el-card>
      <el-form
        :model="payApplyForm"
        :inline="true"
        ref="payApplyFormRef"
        :rules="rules"
        label-width="auto"
        size="mini"
      >
        <!--基本用户信息-->
        <el-row>
          <el-form-item label="申请单号">
            {{initData.applyNo}}
            <el-tooltip effect="light" placement="bottom">
              <div slot="content">
                <div
                  v-html="approveProgressHtmlStr"
                  style="max-width:500px;overflow:auto;background: #e1e5e8;font-size: 15px;line-height: 16px;color: #888;max-height: 320px;"
                ></div>
              </div>
              <i
                style="font-size:20px"
                class="el-icon-s-flag"
              ></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="申请人" style="margin-left: 50px">
            {{initData.applyUserName}}
          </el-form-item>
          <el-form-item label="申请时间" style="margin-left: 50px">
            {{initData.applyTime}}
          </el-form-item>
          <el-form-item label="申请部门" style="margin-left: 50px">
            {{initData.applyDeptName}}
          </el-form-item>
        </el-row>

        <!--第二行-->
        <el-row :gutter="10">
          <!--第一列-->
          <el-col :span="6">
            <el-form-item prop="serveCompanyId" label="公司简称">
              <el-select
                v-model="payApplyForm.serveCompanyId"
                :remote-method="searchServeCompany"
                placeholder="请输入至少两个关键字"
                clearable
                filterable
                remote
                :disabled="serveCompanySelectDisabled"
                @change="queryServeCompanyAccount"
              >
                <el-option
                  v-for="(item, key) in serveCompanyMap"
                  :key="key"
                  :label="item"
                  :value="parseInt(key)">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="applyAmt" label="申请金额">
              <el-input-number v-model="payApplyForm.applyAmt" :min="0" :controls="false" :precision="2" style="width: 190px" :disabled="true"></el-input-number>
            </el-form-item>

            <el-form-item prop="currency" label="币种">
              <el-select
                v-model="payApplyForm.currency"
                filterable
                :disabled="editDisabled"
              >
                <el-option
                  v-for="(item, key) in initData.currencyMap"
                  :key="item"
                  :label="key"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="payDate" label="支付日期">
              <el-date-picker
                v-model="payApplyForm.payDate"
                type="date"
                value-format="yyyy-MM-dd"
                :disabled="editDisabled"
                style="width: 190px"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!--第二列-->
          <el-col :span="10">
            <el-form-item prop="applyRemark" label="申请说明">
              <el-input type="textarea" v-model="payApplyForm.applyRemark" placeholder="请输入" style="width: 600px" :disabled="editDisabled"></el-input>
            </el-form-item>
            <el-form-item prop="serveCompanyAccountId" label="收款账户">
              <el-select
                v-model="payApplyForm.serveCompanyAccountId"
                filterable
                clearable
                style="width: 600px"
                :disabled="editDisabled"
              >
                <el-option
                  v-for="(item, index) in serveCompanyAccountList"
                  :key="item.id"
                  :label="item.accountShowName"
                  :value="parseInt(item.id)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!--附件上传-->
          <el-col :span="7">
            <el-form-item label="附件" :required="true">
              <el-upload
                class="upload-demo"
                drag
                :http-request="fileUpload"
                multiple
                :show-file-list="false"
                :disabled="editDisabled"
                action="test"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
            <el-table
              :data="fileTableData"
            >
              <el-table-column
                prop="fileName"
                label="文件名"
                width="300">
              </el-table-column>
              <el-table-column
                prop="fileSize"
                label="文件大小"
                width="100">
              </el-table-column>
              <el-table-column
                prop="fileType"
                label="文件类型">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-tooltip content="下载">
                    <i
                      style="color:#57dfecfa;"
                      class="el-icon-download pointer margin-right-sm text-xl"
                      @click="fileDownload(scope.$index, scope.row)"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <div class="flex justify-end margin-top">
          <el-button-group>
            <el-button type="primary" size="small" @click="approveRejectPrevNode" :disabled="editDisabled">驳回</el-button>
            <el-button type="primary" size="small" @click="approvePass" :disabled="editDisabled">通过</el-button>
          </el-button-group>
        </div>
      </el-form>
    </el-card>

    <!--新增收款账户弹框-->
    <el-dialog
      title="新增收款账户"
      width="70%"
      :visible.sync="serveCompanyAccountDialogShow"
      :before-close="closeServeCompanyAccountDialog"
    >
      <el-form
        ref="serveCompanyAccountRef"
        :rules="serveCompanyAccountFormRules"
        label-width="100px"
        size="mini"
        :model="serveCompanyAccountForm"
        class="padding-lr-40"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="payee" label="收款人">
              <el-input
                v-model="serveCompanyAccountForm.payee"
                placeholder="请填写收款人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="type" label="账户类型">
              <el-select
                v-model="serveCompanyAccountForm.accountType"
                placeholder="请选择账户类型"
              >
                <el-option v-for="(item,value) in serverAccountTypeMap" :key="value" :label="item" :value="value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="payBank" label="收款银行">
              <el-input
                v-model="serveCompanyAccountForm.payBank"
                placeholder="请填写收款银行"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="bankAccount" label="银行账号">
              <el-input
                v-model="serveCompanyAccountForm.bankAccount"
                placeholder="请填写银行账号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="bankAddress" label="银行地址">
              <el-input
                v-model="serveCompanyAccountForm.bankAddress"
                placeholder="请填写银行地址"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="payBankSwiftCode" label="收款银行 SWIFT CODE">
              <el-input
                v-model="serveCompanyAccountForm.payBankSwiftCode"
                placeholder="请填写收款银行 SWIFT CODE"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="isDefault" label="是否默认">
              <el-radio-group v-model="serveCompanyAccountForm.isDefault">
                <el-radio :label="parseInt(1)">是</el-radio>
                <el-radio :label="parseInt(0)">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitServeCompanyAccountForm('serveCompanyAccountRef')">立即创建</el-button>
        <el-button @click="resetServeCompanyAccountForm('serveCompanyAccountRef')">重置</el-button>
      </div>
    </el-dialog>

    <!--搜索框-->
    <el-card>
      <el-form
        :model="searchForm"
        :inline="true"
        size="mini"
        class="padding-top-sm"
        label-position="left"
        label-width="90px"
      >
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select
                v-model="searchForm.inputUser"
                filterable
                clearable
                placeholder="请选择"
                style="width: 190px"
              >
                <el-option
                  v-for="(item, value) in initData.userMap"
                  :key="value"
                  :label="item"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="应收应付备注">
              <el-input v-model="searchForm.receivePayRemark" placeholder="请输入" style="width: 190px"></el-input>
            </el-form-item>

            <el-form-item prop="accountDate" label="费用时间">
              <el-date-picker
                v-model="searchForm.accountDate"
                unlink-panels
                type="daterange"
                style="width: 190px"
                start-placeholde="开始时间"
                end-placeholde="结算时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>

            <el-form-item label="费用类型">
              <el-select
                v-model="searchForm.costType"
                style="width: 190px"
              >
                <el-option
                  v-for="item in costTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="销售">
              <el-select
                v-model="searchForm.salesManId"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, value) in initData.userMap"
                  :key="value"
                  :label="item"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="费用名称">
              <el-select
                v-model="searchForm.costNames"
                filterable
                clearable
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, value) in initData.costNamesMap"
                  :key="value"
                  :label="item"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="币种">
              <el-select
                v-model="searchForm.currency"
                filterable
              >
                <el-option
                  v-for="(item, key) in initData.currencyMap"
                  :key="item"
                  :label="key"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="运单号">
              <el-input type="textarea" v-model="searchForm.waybillNos" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="参考号">
              <el-input type="textarea" v-model="searchForm.referenceNos" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="M单号">
              <el-input type="textarea" v-model="searchForm.masterNumbers" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="追踪号">
              <el-input type="textarea" v-model="searchForm.trackNumbers" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="flex justify-end margin-top">
          <el-button-group>
            <el-button type="primary" size="mini" @click="exportTableData" :disabled="editDisabled">导出</el-button>
          </el-button-group>
        </div>
      </el-form>
    </el-card>

    <!--销账明细table-->
    <el-card>
      <el-table size="mini" :data="tableData" class="text-sm" id="out-eltable">
        <el-table-column type="index" label="序号"/>
        <el-table-column
          prop="waybillNo"
          label="运单号"
          sortable
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="referenceNo"
          label="参考号"
          sortable
          width="100">
        </el-table-column>
        <el-table-column
          prop="masterNumber"
          sortable
          label="M单号">
        </el-table-column>
        <el-table-column
          prop="inStockTime"
          label="入库日期"
          sortable
        >
        </el-table-column>

        <el-table-column label="费用名称" prop="costNameId" sortable>
          <template slot-scope="scope">
            {{ initData.costNamesMap[scope.row["costNameId"]] }}
          </template>
        </el-table-column>

        <el-table-column
          prop="remain"
          label="余额">
        </el-table-column>

        <el-table-column
          prop="currency"
          label="币种"
          sortable>
        </el-table-column>

        <!--销账金额-->
        <el-table-column prop="offMoney">
          <template slot="header" slot-scope="scope">
            <span>销账金额</span>
            <span class="my_color" @click="selectAll">{{texts ? "全选" : "全不选"}}</span>
          </template>
          <template slot-scope="scope">
            <el-input
              size="mini"
              v-model="scope.row.offMoney"
              @focus="onFocus($event, scope)"
              style="width:120px"
              clearable
            ></el-input>
            <span v-show="false">{{ scope.row.offMoney }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="accountDate"
          label="费用日期"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注信息">
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
  import { ajax } from "@/store/yg/common/utils";
  import { untransform } from "@/store/yg/common/uri";
  import { m } from "@/store/yg/common/local";
  import { clone } from "@/utils/clone";
  import { parseTime } from "@/utils";
  import FileSaver from "file-saver";
  import XLSX from "xlsx";
  import axios from "axios";
  import * as constant from "@/store/yg/common/constant";

  export default {
    data() {
      return {
        serveCompanyAccountForm: {},//新增收款账户表单数据
        serveCompanyAccountDialogShow: false,
        serverAccountTypeMap: {},
        editDisabled: false,
        approveProgressHtmlStr: '',
        payApplyForm: {
          currency: 'RMB'
        },
        serveCompanySelectDisabled: false,
        serveCompanyAccountList: null,//服务商收款账号
        action: "",
        loading: false,
        isShow: false,//总计区域内容显示
        texts: true,
        totalOffResult: "",
        totalDataNum: null, //总计金额
        totalWriteOffTitle: false, //销账总计文字显示
        offCurrencyMap: {},
        selectData: [], //选中的汇率数据
        serveCompanyMap: [],
        initData: {},
        payTypeOptions: [
          {
            value: 1,
            label: '银行卡'
          }, {
            value: 2,
            label: '电汇'
          }],
        costTypeOptions: [
          {
            value: 0,
            label: 'FBA费用'
          }, {
            value: 1,
            label: '海外仓费用'
          }],
        writeoffData: [], // 记账汇率
        offAccountCurrencyRate: [],//汇率(JPY*RMB=1:0.07)
        dialogTableVisible: false,
        showRate: true,
        showInputRate: false,
        rules: {
          applyRemark: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          serveCompanyAccountId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          serveCompanyId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          applyAmt: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          currency: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          payType: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          payDate: [{
            required: true,
            message: '请输入',
            trigger: 'blur'
          }]
        },
        serveCompanyAccountFormRules: {
          payee: [
            { required: true, message: "请填写收款人", trigger: "blur" }
          ],
          accountType: [
            { required: true, message: "请填写账户类型", trigger: "blur" }
          ],
          payBank: [
            { required: true, message: "请选择收款银行", trigger: "blur" }
          ],
          bankAccount: [
            { required: true, message: "请填写银行账号", trigger: "blur" }
          ],
          bankAddress: [
            { required: false, message: "请填写银行地址", trigger: "blur" }
          ],
          payBankSwiftCode: [
            { required: false, message: "请填写收款银行SWIFT CODE", trigger: "blur" }
          ],
          isDefault: [
            { required: true, message: "请选择是否默认", trigger: "chenge" }
          ]
        },
        fileTableData: [],
        tableData: [],//销账明细表格数据
        checkCurrencyResult: true,
        searchForm: {
          costType: 0
        },
      };
    },

    created: function() {
      this.action =
        constant.API_SERVER +
        "/api/consume/upload?uri=" +
        untransform(this.$route.params.uri) +
        "&f=fileUpload&type=blank&name=sub&id=" +
        this.$store.state.edit.id;
    },

    mounted() {
      if (this.$route.query.pid) {
        this.edit();
      } else {
        this.init();
      }
    },

    methods: {

      /**
       * 驳回上一节点
       * */
      async approveRejectPrevNode() {
        let ids = [];
        const id = this.$route.query.pid
        ids.push(id);
        const approveRemark = '待审核付款申请编辑页操作驳回至上一节点';
        const { code, data, message } = await ajax("rejectPrevNode", {
          ids: ids,
          approveRemark: approveRemark
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        this.$message({
          type: "success",
          message: "操作成功！"
        });
      },

      /**
       * 审批通过
       * */
      async approvePass() {
        let ids = [];
        const id = this.$route.query.pid;
        ids.push(id);
        const approveRemark = '待审核付款申请编辑页操作审批通过';
        const { code, data, message } = await ajax("approvePass", {
          ids: ids,
          approveRemark: approveRemark
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        //提示成功
        this.$message({
          type: "success",
          message: "审批成功！"
        });
        //跳转至付款申请列表
        window.location.href = '/#/main/finance__payapply__list';
      },

      //region 新增收款账户相关
      /**
       * 关闭新增收款账户弹框
       * */
      closeServeCompanyAccountDialog() {
        this.serveCompanyAccountDialogShow = false;
        this.resetServeCompanyAccountForm("serveCompanyAccountRef");
      },

      /**
       * 重置新增收款账户表单数据
       * */
      resetServeCompanyAccountForm(refName) {
        this.serveCompanyAccountForm = {
          id: "",
          payee: "",
          accountType: "",
          payBank: "",
          bankAccount: "",
          bankAddress: "",
          payBankSwiftCode: "",
          isDefault: "",
          serverId: ""
        };
        this.$refs[refName].resetFields();
      },

      /**
       * 弹框show
       * */
      async showAddServeCompanyAccountDialog() {
        let serveCompanyId = this.payApplyForm.serveCompanyId;
        if (!serveCompanyId) {
          this.$message.error("请先选择公司简称");
          return;
        }
        //加载账户类型
        ajax("listAccount", { serverId: serveCompanyId },{
          class: "com.tofba.app.client.setting.ServeCompanyAccountClient"
        }).then(
          res => {
            if (res.code == 200) {
              this.serverAccountTypeMap = res.data2;
            } else {
              this.$message.error("数据异常");
            }
          },
          error => {
            console.log(error);
          }
        );
        this.serveCompanyAccountDialogShow = true;
      },

      /**
       * 新增收款账户，校验必填
       * */
      submitServeCompanyAccountForm(refName) {
        this.$refs[refName].validate(valid => {
          if (valid) {
            this.saveServeCompanyAccount();
          } else {
            console.log("数据校验失败，不允许提交");
            return false;
          }
        });
      },

      /**
       * 新增收款账户，保存
       * */
      async saveServeCompanyAccount() {
        this.serveCompanyAccountForm.serverId = this.payApplyForm.serveCompanyId;
        ajax("save", this.serveCompanyAccountForm, {
          class: "com.tofba.app.client.setting.ServeCompanyAccountClient"
        }).then(
          res => {
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
            this.$message({
              message: "保存成功",
              type: "success"
            });
            this.serveCompanyAccountDialogShow = false;
            this.queryServeCompanyAccount();
          },
          error => {
            console.log(error);
          }
        );
      },
      //endregion

      async edit() {
        this.loading = true;
        let applyId = this.$route.query.pid;
        //请求后台
        const { code, data, message } = await ajax("edit", {
          applyId: applyId
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        //是否可编辑（当前待审批人可编辑）
        this.editDisabled = data.editDisabled;

        //页面顶部的基本用户信息
        this.initData.applyNo = data.financePayApply.applyNo;
        this.initData.applyUserName = data.applyUserName;
        this.initData.applyTime = data.financePayApply.applyTime;
        this.initData.applyDeptName = data.applyDeptName;
        this.approveProgressHtmlStr = data.approveProgressHtmlStr;

        //下拉框选项
        this.initData.currencyMap = data.currencyMap;
        this.initData.companyBankMap = data.companyBankMap;
        this.initData.userMap = data.userMap;
        this.initData.costNamesMap = data.costNamesMap;
        this.initData.deptMap = data.deptMap;

        //服务商（公司简称）
        this.serveCompanyMap = data.serveCompanyMap;
        this.serveCompanySelectDisabled = true;

        //收款账户
        let serveCompanyAccountList = data.serveCompanyAccountList;
        for (let account of serveCompanyAccountList) {
          let accountShowName = account.payee + '(' + account.bankAccount + ' ' + account.payBank + account.bankAddress + ')';
          account.accountShowName = accountShowName;
        }
        this.serveCompanyAccountList = serveCompanyAccountList;

        //附件
        this.fileTableData = data.files;
        //申请表单
        this.payApplyForm = data.financePayApply;
        //销账明细
        this.tableData = data.financeReceiveDetails;
        this.loading = false;
      },

      //销账金额输入框获取焦点事件
      onFocus(event, scope) {
        this.$set(scope.row, "offMoney", scope.row.remain);
        event.target.select();
      },

      //导出销账明细
      exportTableData() {
        /* 从表生成工作簿对象 */
        let wb = XLSX.utils.table_to_book(document.querySelector("#out-eltable"));
        /* 获取二进制字符串作为输出 */
        let wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            //Blob 对象表示一个不可变、原始数据的类文件对象。
            //Blob 表示的不一定是JavaScript原生格式的数据。
            //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
            //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
            new Blob([wbout], { type: "application/octet-stream" }),
            //设置导出文件名称
            "销账明细.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      },

      /**
       * 总计
       * */
      amountTotal() {
        let tableData = this.tableData;
        let list = [];
        let allCurrencyMap = new Map();
        let totalAmount = 0;
        let currency = "";
        //筛选出销账金额不为空的
        for (let item of tableData) {
          if (item.offMoney) {
            list.push(item);
          }
        }
        for (let item of list) {
          allCurrencyMap.set(item.currency, item.currency);
          totalAmount += item.offMoney;
        }
        if (allCurrencyMap.size > 1) {
          this.$message.error("不同币种不允许同时申请，请重新选择费用！");
          return;
        }
        //debugger
        for (let item of allCurrencyMap.values()) {
          currency = item;
        }
        //赋值：申请金额和币种
        this.payApplyForm.applyAmt = totalAmount;
        this.payApplyForm.currency = currency;
      },

      //销账金额，全选
      selectAll() {
        this.$nextTick(() => {
          this.texts = !this.texts;
        });
        //全选
        if (this.texts) {
          let tableData = this.tableData;
          if (!(tableData && tableData.length > 0)) {
            return;
          }
          tableData.forEach(item => {
            item.offMoney = item.remain;
          });
        } else {
          //全不选
          let tableData = this.tableData;
          if (!(tableData && tableData.length > 0)) {
            return;
          }
          tableData.forEach(item => {
            item.offMoney = "";
          });
        }
      },

      //附件上传
      fileUpload(params) {
        // debugger
        const file = params.file;
        const form = new FormData();
        // 文件对象
        form.append("items[]", file);
        axios({
          method: "post",
          url: this.action,
          data: form
        })
          .then(response => {
            debugger
            if (response.data.code === 200) {
              let files = response.data.data;
              for (let fileObj of files) {
                fileObj.fileSize = this.formatFileSize(fileObj.fileSize);
                this.fileTableData.push(fileObj);
              }
            }
          })
          .catch(error => {
            console.log(error);
            this.$notify.error({
              title: "错误",
              message: "上传失败!"
            });
          });
      },

      formatFileSize(fileSize) {
        if (fileSize < 1024 * 1024) {
          //显示成“K”
          fileSize = fileSize / 1024;
          fileSize = fileSize.toFixed(2) + "K";
        } else {
          //显示成“M”
          fileSize = fileSize / 1024 / 1024;
          fileSize = fileSize.toFixed(2) + "M";
        }
        return fileSize;
      },

      showInput() {
        this.showRate = false;
        this.showInputRate = true;
      },

      //校验必填
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.commit();
          } else {
            console.log("数据校验失败，不允许提交");
            return false;
          }
        });
      },

      //查询服务商
      async searchServeCompany(query) {
        if (query !== "" && query.length > 1) {
          let res = await ajax("searchServeCompany", {
            arg: query
          });
          this.serveCompanyMap = res;
        }
      },

      //查询初始化数据
      async init() {
        const { code, data, message } = await ajax("getInitData", {});
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        this.initData = data;
        //基本信息保存至payApplyForm
        this.payApplyForm.applyNo = this.initData.applyNo;
        this.payApplyForm.applyUserId = this.initData.applyUserId;
        this.payApplyForm.applyTime = this.initData.applyTime;
        this.payApplyForm.applyDeptId = this.initData.applyDeptId;
      },

      /**
       * 保存
       * 不进行任何校验，直接保存。
       * */
      async save() {
        let applyId = this.payApplyForm.id;
        //销账明细
        let tableData = this.tableData;
        let payments = [];
        //应付
        for (const item of tableData) {
          //选了销账金额才会保存
          if (item.offMoney) {
            let payment = {};
            payment.paymentId = item.waybillReceivePayablesId;
            payment.offMoney = item.offMoney;
            payment.isAbroad= item.isAbroad;
            payment.financePayApplyId = applyId;
            payment.waybillId = item.waybillId;
            payment.costNameId = item.costNameId;
            payments.push(payment);
          }
        }
        this.payApplyForm.payApplyPayments = payments;
        //附件
        let fileTableData = this.fileTableData;
        for (const item of fileTableData) {
          item.applyId = applyId;
        }

        const { code, data, message } = await ajax("save", {
          payApply: this.payApplyForm,
          files: fileTableData
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        //新增成功，后台返回payApplyId
        if (!applyId) {
          this.payApplyForm.id = data;
        }
        this.$message({
          type: "success",
          message: "保存成功！"
        });
      },

      /**
       * 提交付款申请，开启审批流程
       * */
      async commit() {
        let payApplyId = this.payApplyForm.id;
        if (!payApplyId) {
          this.$message.error("请先保存！");
          return;
        }
        //校验：附件不能为空
        if (this.fileTableData.length === 0) {
          this.$message.error("请上传附件");
          return;
        }
        let ids = [];
        ids.push(payApplyId);
        //请求后台
        const { code, data, message } = await ajax("commit", {
          ids: ids
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        this.$message({
          type: "success",
          message: "提交成功！"
        });
        window.location.href = '/#/main/finance__payapply__list';
      },

      /**
       * 查询服务商收款账户
       * */
      async queryServeCompanyAccount() {
        let serverId = this.payApplyForm.serveCompanyId;
        if (!serverId) {
          return;
        }
        const { code, data, message } = await ajax("queryServeCompanyAccount", {
          serverId: serverId
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        let list = data;
        for(let account of list){
          let accountShowName = account.payee+'('+account.bankAccount+' '+account.payBank+account.bankAddress+')';
          account.accountShowName = accountShowName;
        }
        this.serveCompanyAccountList = list;
      },

      //查询销账明细列表数据
      async queryFinanceReceiveDetails() {
        this.loading = true;
        if (this.$route.query.pid !== undefined) {
          this.receiveItemDialogVisible = true;
        }
        //region 查询条件
        let data = {};
        // 服务商id
        let serCusId = this.payApplyForm.serveCompanyId;
        serCusId = 'Ser_' + serCusId;
        if (serCusId) {
          data.serCusId = serCusId;
        }
        // 录入人
        const inputUser = this.searchForm.inputUser;
        if (inputUser) {
          data.inputUser = inputUser;
        }
        // 应收应付备注
        const receivePayRemark = this.searchForm.receivePayRemark;
        if (receivePayRemark) {
          data.receivePaymentReamrk = receivePayRemark;
        }
        //费用时间
        const accountDate = this.searchForm.accountDate;
        if (accountDate && accountDate.length === 2) {
          const startAccountTime = accountDate[0];
          if (startAccountTime) {
            data.startAccountTime = startAccountTime;
          }
          const endAccountTime = accountDate[1];
          if (endAccountTime) {
            data.endAccountTime = endAccountTime;
          }
        }
        //费用类型
        data.costType = this.searchForm.costType;
        //销售
        const salesManId = this.searchForm.salesManId;
        if (salesManId) {
          data.saleId = salesManId;
        }
        // 费用名称
        const costNames = this.searchForm.costNames;
        if (costNames) {
          data.costNames = costNames;
        }

        // 费用币种
        const filterCurrency = this.searchForm.currency;
        if (filterCurrency) {
          data.filterCurrency = filterCurrency;
        }
        //运单号
        const waybillNos = this.searchForm.waybillNos;
        if (waybillNos) {
          data.waybillNos = waybillNos.split("\n");
        }
        //参考号
        const referenceNos = this.searchForm.referenceNos;
        if (referenceNos) {
          data.referenceNos = referenceNos.split("\n");
        }
        //M单号
        const masterNumbers = this.searchForm.masterNumbers;
        if (masterNumbers) {
          data.masterNumbers = masterNumbers.split("\n");
        }
        //追踪号
        const trackNumbers = this.searchForm.trackNumbers;
        if (trackNumbers) {
          data.trackNumbers = trackNumbers.split("\n");
        }
        //endregion
        let res = await ajax("queryFinanceReceiveDetails", data);
        this.tableData = res.data.tableData;
        //给“待支付余额”赋值
        let tableData = this.tableData;
        let totalRemain = 0;
        tableData.forEach(item => {
          totalRemain += item.remain;
        });
        this.payApplyForm.toPayAmt = totalRemain;
        this.costNamesMap = res.data.costNamesMap;
        this.loading = false;
      },

      //附件下载
      fileDownload(index, row) {
        let filePath = row.filePath;//  "/data/upload/tmp/upload/测试上传附件20211112b28.xlsx"
        let fileName = encodeURIComponent(row.fileName);// 测试上传附件20211112b28.xlsx
        let server = constant.FILE_SERVER;
        let fileUrl = server + filePath;
        location.href = constant.API_SERVER + "/open/downloadFileByHttp?path=" + fileUrl + "&fileName=" + fileName;
      }
    }
  };
</script>


<style>
  .my_color {
    color: #ff7575;
    cursor: pointer;
  }
  .my_left {
    margin-left: 54px;
  }

</style>
